package cn.taobaoke.restful.task;

import cn.taobaoke.restful.datasource.DynamicDataSourceContextHolder;
import cn.taobaoke.restful.domain.DomainEntity;
import cn.taobaoke.restful.domain.DomainRepository;
import cn.taobaoke.restful.domain.RobotEntity;
import cn.taobaoke.restful.domain.RobotRepository;
import cn.taobaoke.restful.util.DateUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 当机器人的更新状态超过<em>15分钟</em>未更新则更新器状态为<em>error</em>.
 * @author yangzuo
 * @since 2017-04-24 14:17
 */
@Component("CheckRobotStatusTask")
@Scope("prototype")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CheckRobotStatusTask extends Thread {

    @Override
    public void run() {
        logger.info("Start CheckRobotStatusTask");
        while (true) {
            try {
                sleep(INTERVAL);
                logger.info("Execute Checking Robot Status Task");
                checkRobotStatus();
            } catch (Exception e) {
                logger.error("Task of monitoring robot status failed", e);
            }
        }
    }

    private void checkRobotStatus() {
        List<RobotEntity> list = robotRepository.findAll();
        logger.debug("Checking Robot Status, size={}", list.size());

        Date now = new Date();
        List<RobotEntity> updateList = new ArrayList<>();
        for (RobotEntity robot: list) {
            if (DateUtil.dateTimeDiff(now, robot.getUpdateAt()) > INTERVAL
                    && ! CLOSE.equals(robot.getState()) && ! ERROR.equals(robot.getState())) {
                robot.setState(ERROR);
                updateList.add(robot);
            }
        }
        if (updateList.size() > 0) {
            logger.debug("Number of timeout robot: {}", updateList.size());
            robotRepository.saveAll(updateList);
        }
    }

    private final @NonNull RobotRepository robotRepository;

    private static Logger logger = LogManager.getLogger(CheckRobotStatusTask.class);

    private final static long INTERVAL = 15 * 60 * 1000L; // 15分钟间隔
    private final static String ERROR = "error";
    private final static String CLOSE = "close";
}
